/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { Scene, SceneConfig } from "arkanalyzer";
import Logger, { LOG_MODULE_TYPE } from "arkanalyzer/lib/utils/logger";
import { buildModuleChains } from "./BuildModuleChains";
import { ProjectConfig } from "../model/ProjectConfig";
import { FileUtils } from "../utils/common/FileUtils";
import { Utils } from "../utils/common/Utils";

const logger = Logger.getLogger(LOG_MODULE_TYPE.TOOL, 'runTool');

export function runTool(tool: Tools, projectConfig: ProjectConfig) {
    const startTime = new Date().getTime();
    try {
        // 配置日志文件路径
        const logPath = projectConfig.logPath;
        Utils.setLogPath(logPath.length ? logPath : './HomeCheckTools.log');
        logger.info('start to run tool...');
        const scene = buildScene(projectConfig);
        if (!scene) {
            return;
        }
        // 运行对应工具模块
        switch (tool) {
            case Tools.ImportChains:
                logger.info('start to buildModuleChains...');
                buildModuleChains(scene, [], projectConfig.reportDir);
                logger.info('buildModuleChains completed.');
                break;
            default:
                logger.error(`Unknown tool: ${tool}`);
                break;
        }
    } catch (error) {
        logger.error(`Error occurred: ${(error as Error).message}`);
        return;
    }
    const endTime = new Date().getTime();
    logger.info(`HomeCheck tools took: ${(endTime - startTime) / 1000}s`);
}

function buildScene(projectConfig: ProjectConfig): Scene | null {
    try {
        // 构建SceneConfig
        const config: SceneConfig = new SceneConfig();
        const fileList = FileUtils.getAllFiles(projectConfig.projectPath, ['.ts', '.ets']);
        config.buildFromProjectFiles(projectConfig.projectName, projectConfig.projectPath, fileList, FileUtils.genSdks(projectConfig));
        logger.info('Build sceneConfig completed.');
        // 构建Scene
        const scene = new Scene();
        scene.buildSceneFromFiles(config);
        logger.info('Build scene completed.');
        scene.inferTypes();
        logger.info('Infer types completed.');
        return scene;
    } catch (error) {
        logger.error(`Build scene or infer types error: ${(error as Error).message}`);
        return null;
    }
}

export enum Tools {
    ImportChains = 0
}